import { useEffect, useRef } from 'react';
import type { Message } from '../types/chat';
import { MarkdownMessage } from './MarkdownMessage';
import './MessageList.css';

interface MessageListProps {
  messages: Message[];
  isLoading?: boolean;
}

export function MessageList({ messages, isLoading }: MessageListProps) {
  const messagesEndRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isLoading]);

  return (
    <div className="message-list">
      {messages.length === 0 ? (
        <div className="message-list-empty">
          <div className="message-list-empty-icon">💬</div>
          <div className="message-list-empty-text">开始你的对话吧</div>
        </div>
      ) : (
        messages.map((message) => (
          <div
            key={message.id}
            className={`message-item message-item-${message.role}`}
          >
            <div className="message-avatar">
              {message.role === 'user' ? '👤' : '🤖'}
            </div>
            <div className="message-content">
              <div className="message-text">
                <MarkdownMessage content={message.content} role={message.role} />
              </div>
              <div className="message-time">
                {message.timestamp.toLocaleTimeString('zh-CN', {
                  hour: '2-digit',
                  minute: '2-digit',
                })}
              </div>
            </div>
          </div>
        ))
      )}
      {isLoading && (
        <div className="message-item message-item-assistant">
          <div className="message-avatar">🤖</div>
          <div className="message-content">
            <div className="message-loading">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      )}
      <div ref={messagesEndRef} />
    </div>
  );
}

